package org.luu.medicare.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.luu.medicare.common.Result;

import org.luu.medicare.entity.TPrescriptionDetail;
import org.luu.medicare.repository.TPrescriptionDetailRepo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


import java.util.Optional;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class PrescriptionService {
    private final TPrescriptionDetailRepo prescriptionRepository;

    public Result<String> save(TPrescriptionDetail prescription) {
        prescriptionRepository.save(prescription);
        return Result.success();
    }

    public Result<String> update(TPrescriptionDetail prescription) {
        Optional<TPrescriptionDetail> detail = prescriptionRepository.findById(prescription.getId());
        if (detail.isPresent()) {
            prescriptionRepository.save(prescription);
            return Result.success();
        }
        return Result.error("Prescription not found");
    }

    public Result<String> deleteById(Integer id) {
        Optional<TPrescriptionDetail> detail = prescriptionRepository.findById(id);
        if (detail.isPresent()) {
            prescriptionRepository.deleteById(id);
            return Result.success();
        }
        return Result.error("Prescription not found");
    }

    public Result<TPrescriptionDetail> findById(Integer id) {
        Optional<TPrescriptionDetail> detail = prescriptionRepository.findById(id);
        return detail.map(Result::success).orElseGet(() -> Result.error("Prescription not found"));
    }

}
